package com.citybrain.rnapp.service;

import java.io.File;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;


/**
 * Created by DYH on 2019/6/7 0007.
 */
public class RecordAudioService extends Service {

    private static final String TAG="RecordAudioService";

    public static final String ACTION_START_RECORD = "startRecord";

    public static final String ACTION_STOP_RECORD = "stopRecord";

    private File soundFile;
    private String soundPath;

    private MediaRecorder mRecorder;

    private static final String SERVICE_NAME = "RecordAudioService";

    public static final String ACTION_SEND = "com.iwhalecloud.iwhalechat.onVoiceRecordEnd";

    // "startRecord", // 开始录音接口
    // "stopRecord", // 停止录音接口
    // "onVoiceRecordEnd", // 监听录音自动停止接口
    // "uploadVoice", // 上传语音接口
    private TimerThread timerThread;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        timerThread = new TimerThread();
        timerThread.start();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        // 每次都要进来 可以做初始化
    }

    boolean isLoop = false;

    boolean isStop=false;

    /**
     * 计时器不需要 因为只需要结束时间 所以开始录音就记录一个起始时间
     * 结束录音就 用当前时间减去即可 这样不需要操作线程 （线程同步问题暂时无法处理妥当）
     * 线程不控制录音 只是计时
     */

    public volatile long starTime = 0;

    public volatile long nowTime = 0;

    /* 记录时间 */
    private volatile float mTime=0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent != null) {
            String action = intent.getAction();
            if (action != null) {
                if (action.equals("startRecord")) {
                    // 开始录音
                    Log.i("dyh", "开始录音");
                    stop();
                    starTime = System.currentTimeMillis();
                    isLoop =true;
                    mTime =0;
                    initAudio();


                }
                else if (action.equals("stopRecord")) {
                    Log.i("dyh", "stopRecord");
                    stopRecord(1);
                }
                else {
                    Log.i("dyh", "传了啥子哟");
                }
            }

        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        stop();
        isStop=true;
        super.onDestroy();
    }

    /**
     * 在SD卡上创建目录
     *
     * @param dirName
     */
    public File creatSDDir(String dirName) {
        File dir = new File(Environment.getExternalStorageDirectory() + "/" + dirName);
        dir.mkdirs();
        return dir;
    }

    public synchronized  void initAudio() {
        try {
            // 创建保存录音的音频文件
            creatSDDir("Audio");
            soundFile = new File(Environment.getExternalStorageDirectory() + "/loveAudio/" + System.currentTimeMillis() + ".m4a");
            soundPath=soundFile.getAbsolutePath();
            Log.i("dyh", soundFile.getAbsolutePath());
            mRecorder = new MediaRecorder();
            // 设置录音的声音来源
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            // 设置录制的声音的输出格式（必须在设置声音编码格式之前设置）
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            // 设置声音编码的格式
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mRecorder.setOutputFile(soundFile.getAbsolutePath());
            mRecorder.prepare();
            if (mRecorder != null) {
                mRecorder.start();
            }

        }
        catch (Exception e) {
            // e.printStackTrace();
        }
    }

    public void stop() {
        // 停止录音
        isLoop=false;
        try {
            if (mRecorder != null) {
                mRecorder.stop();
                mRecorder.release();
                mRecorder = null;
            }
        }
        catch (Exception e) {

        }
    }



    public synchronized void stopRecord(int i) {
        // 停止录音
        stop();
        nowTime = System.currentTimeMillis();
        if (nowTime - starTime > 1000) {

            if(soundPath!=null)
            {
                // 发送广播 调用前端去 向上兼容 使用动态广播注册
                Intent intent = new Intent(ACTION_SEND);
                intent.putExtra("fileName", soundFile.getAbsolutePath());
                intent.putExtra("auto", i + "");
                intent.putExtra("time", (int) (nowTime - starTime) / 1000 + "");
                RecordAudioService.this.sendBroadcast(intent);
                starTime=nowTime;
                soundPath=null;
            }
        }else{
            if(soundPath!=null)
            {
                new File(soundPath).delete();
                soundPath=null;
            }
        }

    }

    class TimerThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!isStop) {

                while (isLoop){
                    try {
                        Thread.sleep(100);
                        mTime += 0.1f;
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.i("dyh", "计时：" + mTime + "秒");
                    if (mTime > 60) {
                        // 停止子循环 其他属于正常录音，读文件时间即可；
                        RecordAudioService.this.stopRecord(2);
                    }

                }

            }
        }

    }

}
